package com.wenqiner.requesttool.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;

/**
 * @author ranhaifeng
 */
public class CommonUtil {

    public static Date getNextDay(Date date) {
        date = DateUtil.offsetDay(date, 1);
        return DateUtil.beginOfSecond(date);
    }

    /**
     * 获取某一天的第一秒的时间
     *
     * @return date
     **/
    public static Date getFirstSecondDate(Date date) {
        String dateStr = DateUtil.format(date, "yyyy-MM-dd 00:00:00");
        return DateUtil.parse(dateStr, DatePattern.NORM_DATETIME_PATTERN);
    }

    /**
     * 获取某一天的最后一秒的时间
     *
     * @return date
     **/
    public static Date getLastSecondDate(Date date) {
        String dateStr = DateUtil.format(date, "yyyy-MM-dd 23:59:59");
        return DateUtil.parse(dateStr, DatePattern.NORM_DATETIME_PATTERN);
    }

    /**
     * 将一个时区的时间转为另一个时区的时间
     *
     * @param fromDate    来源的时间
     * @param fromZoneStr 来源时区
     * @param toZoneStr   目标时区
     * @date 2022/9/14 15:36
     **/
    public static Date translateDateTimeToOtherDateTime(Date fromDate,
                                                        String fromZoneStr,
                                                        String toZoneStr) {
        ZoneId fromZone;
        if (StrUtil.isNotBlank(fromZoneStr)) {
            fromZone = ZoneId.of(fromZoneStr);
        } else {
            fromZone = ZoneId.systemDefault();
        }
        ZoneId toZone;
        if (StrUtil.isNotBlank(toZoneStr)) {
            toZone = ZoneId.of(toZoneStr);
        } else {
            toZone = ZoneId.systemDefault();
        }
        LocalDateTime ldt = LocalDateTimeUtil.of(fromDate.getTime(), toZone);
        ZonedDateTime zonedDateTimeFrom = ldt.atZone(fromZone);
        ZonedDateTime zonedDateTimeTo = zonedDateTimeFrom.withZoneSameInstant(toZone);
        Date to = Date.from(zonedDateTimeTo.toInstant());
        return to;
    }

    public static Date translateTimestampToOtherDateTime(Long timestamp,
                                                         String toZoneStr) {
        ZoneId toZone = ZoneId.of(toZoneStr);
        LocalDateTime ldt = LocalDateTimeUtil.of(timestamp, toZone);
        ZonedDateTime zonedDateTimeTo = ldt.atZone(toZone);
        Date to = Date.from(zonedDateTimeTo.toInstant());
        return to;
    }

//    public static void main(String[] args) {
//        System.out.println(translateDateTimeToOtherDateTimeStr(new Date(), "GMT+2", DatePattern.NORM_DATETIME_PATTERN));
//        System.out.println(translateZoneDateTimeToOtherDateTimeStr(new Date(), "GMT+2", "GMT+8", DatePattern.NORM_DATETIME_PATTERN));
//        System.out.println(translateZoneDateTimeToOtherDateTimeStr(new Date(), "GMT+8", "GMT+2", DatePattern.NORM_DATETIME_PATTERN));
//    }
//    public static boolean needDecrypt(MethodParameter parameter) {
//
//        boolean classPresent = parameter.getContainingClass().isAnnotationPresent(ValidRequest.class);
//
//        if (classPresent) {
//            return true;
//        } else if (parameter.getMethod() == null) {
//            return false;
//        }
//        return parameter.getMethod().isAnnotationPresent(ValidRequest.class);
//    }


    public static String json(InputStream inputStream) {
        if (inputStream == null) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            char[] charBuffer = new char[215];
            int bytesRead = -1;
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                stringBuilder.append(charBuffer, 0, bytesRead);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }


//    /**
//     * 将 Map对象转化为JavaBean
//     */
//    public static <T> T convertMap2Bean(Map<String, String> map, Class<T> T)
//            throws Exception {
//        if (map == null || map.size() == 0) {
//            return null;
//        }
//        Object mvalue = null;
//        Map<String, Object> newMap = new HashMap<>();
//        for (Map.Entry<String, String> stringObjectEntry : map.entrySet()) {
//            String key = stringObjectEntry.getKey();
//            mvalue = map.get(key);
//            newMap.put(key.toUpperCase(Locale.US), mvalue);
//        }
//
//        BeanInfo beanInfo = Introspector.getBeanInfo(T);
//        T bean = T.newInstance();
//        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
//        for (PropertyDescriptor descriptor : propertyDescriptors) {
//            String propertyName = descriptor.getName();
//            String upperPropertyName = propertyName.toUpperCase();
//
//            if (newMap.containsKey(upperPropertyName)) {
//                Object value = newMap.get(upperPropertyName);
//                //这个方法不会报参数类型不匹配的错误。
////                BeanUtils.copyProperty(bean, propertyName, value);
//            }
//        }
//        return bean;
//    }
//    // 循环左移
//    public static byte[] rotateLeft(byte[] sourceBytes, int n) {
//        byte[] out = new byte[sourceBytes.length];
//        for (int i = 0; i < sourceBytes.length; i++) {
//            out[i] = rotateLeft(sourceBytes[i], n);
//        }
//        return out;
//    }
//
//    public static byte[] rotateRight(byte[] sourceBytes, int n) {
//        byte[] out = new byte[sourceBytes.length];
//        for (int i = 0; i < sourceBytes.length; i++) {
//            out[i] = rotateRight(sourceBytes[i], n);
//        }
//        return out;
//    }
//    private static final ObjectMapper mapper = new ObjectMapper();

//    public static <T> T parseJsonToBean(String content, Class<T> valueType) throws JsonProcessingException {
//        return mapper.readValue(content, valueType);
//    }

//    public static <T> String parseBeanToJson(T t) throws JsonProcessingException {
//        return mapper.writeValueAsString(t);
//    }


    public static String getValue() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < 16; i++) {
            int number = random.nextInt(2);
            long result = 0;
            switch (number) {
                case 0:
                    result = Math.round(Math.random() * 25 + 65);
                    sb.append((char) result);
                    break;
                case 1:
                    result = Math.round(Math.random() * 25 + 97);
                    sb.append((char) result);
                    break;
                default:
                    break;
            }
        }
        String values = sb.toString();
        random = null;
        sb = null;
        return values;
    }

    /**
     * UUID with no character "-"
     *
     * @date 2022-03-24 19:41:05
     */
    public static String randomUuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 集合拷贝
     *
     * @param collection 集合
     * @param targetType 类型
     * @return java.util.List<T>
     **/
    public static <T> List<T> copyToList(Collection<?> collection, Class<T> targetType) {
        return BeanUtil.copyToList(collection, targetType, CopyOptions.create().ignoreNullValue().ignoreError());
    }

    /**
     * <pre>
     * 生成随机整数
     * </pre>
     *
     * @param size 整数位数
     * @return 整数字符串
     **/
    public static String getRandomInt(Integer size) {
        Random random = new Random();
        int bound = 10;
        StringBuilder randomInt = new StringBuilder();
        for (int i = 0; i < size; i++) {
            randomInt.append(random.nextInt(bound));
        }
        return randomInt.toString();
    }

    /**
     * <pre>
     * 返回随机生成的颜色值
     * </pre>
     *
     * @return 颜色编码
     **/
    public static String randomColor() {
        String[] arr = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
        int arrIndexBound = 15;
        Random random = new Random();
        StringBuilder color = new StringBuilder("#");
        for (int i = 0; i < 6; i++) {
            String hex = arr[random.nextInt(arrIndexBound)];
            color.append(hex);
        }
        return color.toString();
    }

    /**
     * 格式化json
     *
     * @param obj 参数
     * @return java.lang.String
     * @author rhf
     */
    public static String formatJson(Object obj) {
        if (null == obj) {
            return null;
        }
        if (obj instanceof String) {
            if (CharSequenceUtil.isBlank(obj.toString())) {
                return "";
            }
            if (!JSON.isValid(obj.toString())) {
                return obj.toString();
            }
            JSONObject jsonObject = JSON.parseObject(obj.toString());
            return JSON.toJSONString(jsonObject, JSONWriter.Feature.PrettyFormat);
        }
        return JSON.toJSONString(obj, JSONWriter.Feature.PrettyFormat);
    }

    /**
     * json解析成对象
     *
     * @param jsonStr json
     * @return java.lang.Object
     * @author rhf
     */
    public static Object parseJson(String jsonStr) {
        if (!JSON.isValid(jsonStr)) {
            return JSONObject.parseObject(jsonStr);
        }
        return jsonStr;
    }
}